package com.lepu.app.fun.chat.business;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.util.Log;

import com.app.application.MyApplication;
import com.app.utils.LoginUtil;
import com.app.utils.Setting;
import com.core.lib.utils.main.LogUtilBase;
import com.lepu.app.fun.chat.bean.ChatError;
import com.lepu.app.fun.chat.bean.Media;
import com.lepu.app.fun.chat.bean.ResultData;
import com.lepu.app.fun.chat.business.chatcore.ChatManager;
import com.lepu.app.fun.chat.business.chatcore.MessageBuilder;
import com.lepu.app.fun.chat.util.StorageManager;
import com.lepu.app.usercenter.bean.LoginInfo;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import common.db.Constants;

/**
 * Created by guolchen on 2014/12/17.
 */
public class MediaManager {

    //    private static Logger logger = LoggerFactory.getLogger(MediaManager.class);
    private MediaListener mediaListener;

    public interface MediaListener {
        void onUpload(Media media);

        void onDownload(Media media);

        void onMediaError(long sessionId, String messageId, Media media, ChatError chatError);
    }

    static class MediaManagerHolder {
        static MediaManager mediaManager = new MediaManager();
    }

    public static MediaManager getInstance() {
        return MediaManagerHolder.mediaManager;
    }

    private MediaManager() {
        this.mediaListener = ChatManager.getInstance();
    }

    public void uploadImage(Media media) {
//        Bitmap bitmap = BimpUtils.resize2CommonImage(media.getFullName());
//        String endPath = SdLocal.getCacheImagePath(MyApplication.getInstance(), LoginUtil.getUserId(), String.valueOf(System.currentTimeMillis()));
//        LogUtilBase.LogD("sendmessage_local_uploadimage", endPath == null ? "" : endPath);
//        try {
//            ImageCompressUtils.saveBitmap(bitmap, endPath);
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
        try {
             // media.setContent(BimpUtils.compressImage2Bytes(bitmap));

           // media.setFullName(endPath);
            uploadFile(media);
        } catch (Exception e) {
            // logger.error(e.toString(), e);
            mediaListener.onMediaError(media.getSessionId(), media.getMessageId(), media, MessageBuilder.buildError(Constants.Error.MEDIA_UPLOAD_ERROR, e));
        }
    }

    //byte[] content = readFileSdcardFile("/storage/sdcard0/record/recorder/录音03.amr");
    public void uploadAudio(Media media) {
        try {
            byte[] content = readFile(media.getFullName());
            if (null != content) {
                media.setContent(content);
                ResultData map = uploadFile(media);
//
//                if (map.getCode() == Constants.SERVER_SUCCESS) {
//                    media.setObjectId(map.getJsonObject().getString("object_id"));
//                    mediaListener.onUpload(media);
//                } else {
//                    mediaListener.onMediaError(media.getSessionId(), media.getMessageId(), media, MessageBuilder.buildError(Constants.Error.MEDIA_UPLOAD_ERROR, map.getCode() + map.getReason()));
//                }
            }
        } catch (Exception e) {
            // logger.error(e.toString(), e);
        }
    }

    public void uploadVideo(Media media) {
    }

    public void downloadImage(final Media media) {
        String path = "";
        if (media.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_IMAGE) {
            path = media.getThumbnailImageId();
        } else if (media.getMessageType() == Constants.Chat.CHAT_MESSAGE_TYPE_AUDIO) {
            path = media.getObjectId();
        }
        HttpUtils http = new HttpUtils();
        //之后需要换
         String a[] = media.getObjectId().split(Setting.URL_API_HOST_HTTP_IMG);
        //String a[] = media.getObjectId().split(Setting.CUTURL);

        http.download(path, new StorageManager().rootChatDir + a[1]
                , true, true, new RequestCallBack<File>() {
            public void onStart() {

            }

            @Override
            public void onLoading(long total, long current, boolean isUploading) {
                Log.i("", current + "/" + total);
            }

            @Override
            public void onFailure(HttpException error, String msg) {
                Log.i("", msg);
            }

            @Override
            public void onSuccess(ResponseInfo<File> responseInfo) {
                Log.i("", "downloaded:" + responseInfo.result.getPath());
                media.setFileName(responseInfo.result.getPath());
                media.setFullName(responseInfo.result.getPath());
                media.setObjectId(responseInfo.result.getPath());
// media.(responseInfo.result.getPath());
// objectFile = media.getLocalObjectFileName();
                mediaListener.onDownload(media);
            }
        });
    }

    public void downloadVideo(Media media) {

    }

    public ResultData uploadFile(final Media media) throws Exception {
        JSONObject params = new JSONObject();
        params.put("DeviceID", String.valueOf(Setting.DEVICEID));
        params.put("ApplicationID", Setting.APPLICATIONID);
        params.put("UserID", LoginUtil.getUserId());
        params.put("LoginToken", LoginUtil.getLoginToken());
        final RequestParams requestParams = new RequestParams();
        if (media.getMimeType().contains("image")) {
            params.put("MimeType", 1);
            LogUtilBase.LogD(" mediamanager  send Photo url:", media.getFullName());
            requestParams.addBodyParameter("File", new File(media.getFullName()));
        } else if (media.getMimeType().contains("audio")) {
            params.put("MimeType", 2);
            requestParams.addBodyParameter("File", new File(media.getFullName()));
        }
        //-------------------------------------------------
        requestParams.addBodyParameter("ht", params.toString());
        HttpUtils httpUtils = new HttpUtils();
        httpUtils.send(HttpRequest.HttpMethod.POST,
                Setting.getUpdateImageURL(), requestParams, new RequestCallBack<Object>() {
            @Override
            public void onSuccess(ResponseInfo<Object> responseInfo) {
                JSONObject jsonObject = null;
                try {
                    jsonObject = new JSONObject((String) responseInfo.result);
                    String state = jsonObject.optJSONObject("Result").optString("Status");
                    if (!state.equals("200"))
                        return;
                    String objectId = jsonObject.optJSONObject("Result").optJSONObject("DetailInfo").optString("FileUrl");
                    String thum = "";
                    String[] sourceStrArray = objectId.split("\\.");
                    if (sourceStrArray != null && sourceStrArray.length > 1) {
                        String str[] = objectId.split("\\." + sourceStrArray[sourceStrArray.length - 1]);
                        if (str[0] != null) {
                            thum = str[0] + "_W_200_V." + sourceStrArray[sourceStrArray.length - 1];
                        }
                    }
                    media.setObjectId(objectId);
                    media.setThumbnailImageId(thum);
                    media.setLargeImageId(objectId);
                    mediaListener.onUpload(media);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(HttpException e, String s) {
                LogUtilBase.LogD("mediaManager update is error", s + "");
            }
        });
        return null;
    }

    public interface AsyncRequest {
        void RequestComplete(Object object, Object data);

        void RequestError(final Object object, int errorId, String errorMessage);
    }

    private byte[] readFile(String fileName) throws IOException {
        byte[] buffer = null;
        try {
            FileInputStream fin = new FileInputStream(fileName);
            int length = fin.available();
            buffer = new byte[length];
            fin.read(buffer);
            fin.close();
        } catch (Exception e) {
            // logger.error(e.toString(), e);
        }
        return buffer;
    }

    //TODO Chang need to save download file to local storage
//    private boolean saveFile(Media media) {
//        //TODO Chang hardcoded file name
//        String newFile = StorageManagerUtils.getInstance().getNewAudioFileName(media.getObjectId(), "amr");
//        media.setFullName(StorageManagerUtils.getInstance().getFullFileName(newFile, media.getSessionId()));
//
//        return StorageManagerUtils.getInstance().SaveAudio(media.getFullName(), media.getContent());
//
//    }

    private String getFileName(String filePath) {
        int start = filePath.lastIndexOf("/");
        int end = filePath.lastIndexOf(".");
        if (start != -1 && end != -1) {
            return filePath.substring(start + 1, end);
        } else {
            return null;
        }
    }

}

